import { ElMessage } from 'element-plus'
//导入axios  npm install axios
import axios from 'axios';
import {useTokenStore} from "@/stores/token.js";


//定义一个变量,记录公共的前缀  ,  baseURL
// const baseURL = 'http://localhost:8080';
const baseURL = '/api';
const instance = axios.create({baseURL})


instance.interceptors.request.use(
    (config)=>{
        //请求前的回调
        //添加token
        const tokenStore = useTokenStore();
        if (tokenStore.token){
            config.headers.Authorization=tokenStore.token
        }
        return config
    },
    (err)=>{
        //请求错误的回调
        Promise.reject(err)
    }
)

// import {useRoute} from "vue-router";
// const router=useRoute();
import router from "@/router/index.js";


//添加响应拦截器
instance.interceptors.response.use(
    result=>{
        if (result.data.code===0){
            return result.data;
        }
        ElMessage.error(result.data.msg?result.data.msg:"服务异常")
        // alert(result.data.msg?result.data.msg:"服务异常")
        //异步操作的状态转化为失败
        return  Promise.reject(result.data)
    },
    err=>{
        //判断状态码 未登录提示登录
        if (err.response.status==401){
            ElMessage.error('请先登录')
            router.push('/')
        }else {
            ElMessage.error('服务异常')
        }
        ElMessage.error('服务异常')
        // alert('服务异常');
        return Promise.reject(err);//异步的状态转化成失败的状态
    }
)

export default instance;
